/*
 * Created by Wildish on 2016-11-01
 *
 * Contact me with keithknight@qq.com
 *
 * Copyright (c) 2016 Wildish
 */

package com.wildish.hybridframework.jsbinding;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Base64;
import android.webkit.WebView;
import android.widget.Toast;

import com.chinark.apppickimagev3.ui.PhotoWallActivity;
import com.chinark.apppickimagev3.utils.ImagePickResult;
import com.chinark.apppickimagev3.utils.ScreenUtils;
import com.wildish.hybridframework.R;
import com.wildish.hybridframework.activity.ViewPagerActivity;
import com.wildish.hybridframework.activity.WebViewActivity;
import com.wildish.hybridframework.core.HybridGlobal;
import com.wildish.hybridframework.jsbinding.webview.JsHelper;
import com.wildish.hybridframework.jsbinding.webview.WebViewBundle;
import com.wildish.hybridframework.scanqrcode.CaptureActivity;
import com.wildish.hybridframework.utils.audio.MediaPlayerHelper;
import com.wildish.hybridframework.utils.audio.SoundItem;
import com.wildish.hybridframework.utils.file.FileUtil;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class HybridSchemeActivity extends Activity {
    private static final int REQUEST_CODE_CAMERA = 0;
    private static final int REQUEST_CODE_SCANQRCODE = 2;

    private Activity me;
    private String photoPath;
    private JSONObject params;
    private WebView currWebview;


    private static final int MSG_GOBACKWARD = 1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_GOBACKWARD:
                    currWebview.loadUrl(JsHelper.createCallback("backward_cb", String.valueOf(msg.obj)));
                    HybridSchemeActivity.this.finish();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        me = this;

        ScreenUtils.initScreen(this);
        Uri uri = getIntent().getData();
        boolean shouldFinish = false;
        if (uri != null) {
            logRequest(uri);
            try {
                String host = uri.getHost();
                params = new JSONObject();
                if (StringUtils.isNotBlank(uri.getQuery())) {
                    String paramStr = uri.getQuery();
                    params = new JSONObject(new String(Base64.decode(paramStr.getBytes(), Base64.DEFAULT)));
                }
                HybridGlobal.logger.log("请求参数:" + params.toString());

                switch (host) {
                    case "takephoto":
                        doTakePhoto();
                        break;
                    case "cancelwebview":
                        shouldFinish = true;
                        cancelWebview();
                        break;
                    case "cancelallwebview":
                        shouldFinish = true;
                        cancelAllWebview();
                        break;
                    case "newwin":
                        shouldFinish = true;
                        showNewWin();
                        break;
                    case "gobackward":
                        currWebview = HybridGlobal.getCurrentWebView();
                        currWebview.post(new Runnable() {
                            @Override
                            public void run() {
                                Message message = new Message();
                                message.what = MSG_GOBACKWARD;
                                message.obj = currWebview.canGoBack();
                                handler.sendMessage(message);
                            }
                        });
                        break;
                    case "showimages":
                        shouldFinish = true;
                        showImages();
                        break;
                    case "takealbum":
                        HybridGlobal.getInstance().updateGallery();
                        Intent intent = new Intent(me, PhotoWallActivity.class);
                        startActivity(intent);
                        break;
                    case "scanqrcode":
                        goScanQRCode();
                        break;

                    case "loadaudio":
                        shouldFinish = true;
                        doLoadAudio();
                        break;
                    case "playaudio":
                        shouldFinish = true;
                        String playKey = params.optString("key");
                        String status = params.optString("status");
                        if (StringUtils.isNotBlank(playKey) && StringUtils.isNotBlank(status)) {
                            HybridGlobal.getInstance().getSoundHelper().playSound(playKey, status);
                        }
                        break;
                    case "closeaudio":
                        shouldFinish = true;
                        HybridGlobal.getInstance().closeMediaVoice();
                        break;
                    case "openaudio":
                        shouldFinish = true;
                        HybridGlobal.getInstance().openMediaVoice();
                        break;
                    case "releaseall":
                        shouldFinish = true;
                        // 释放所有的音频文件
                        HybridGlobal.getInstance().getSoundHelper().releaseAll();
                        break;
                    case "takecall":
                        shouldFinish = true;
                        String phone = params.optString("phone");
                        takeCall(phone);
                        break;
                    case "getlocaltempfoldersize":
                        shouldFinish = true;
                        long filesize = FileUtil.fileSize(HybridGlobal.getTempFolder());
                        HybridGlobal.getCurrentWebView().loadUrl(JsHelper.createCallback("getlocaltempfoldersize", "{\"success\": true, \"filesize\": \"" + filesize + "\"}"));
                        break;
                    case "clearcache":
                        shouldFinish = true;
                        boolean tempFlag = FileUtil.delDir(HybridGlobal.getTempFolder());
                        HybridGlobal.getCurrentWebView().loadUrl(JsHelper.createCallback("clearcache", "{\"success\": " + tempFlag + "}"));
                        break;
                    default:
                        // 默认js-binding形式
                        shouldFinish = true;
                        String className = host.substring(0, host.lastIndexOf("."));
                        String methodName = host.substring(host.lastIndexOf(".") + 1);
                        String fullClassName = String.format("%s.%s", HybridGlobal.getInstance().getPackageName(), className);

                        Class<?> clazz = Class.forName(fullClassName);
                        JsHelper helper = (JsHelper) clazz.newInstance();
                        helper.setParameter(params);
                        Method method = clazz.getMethod(methodName, new Class[]{});
                        method.setAccessible(true);
                        String msg = (String) method.invoke(helper, new Object[]{});

                        String key = params.optString("key");
                        WebView webView = JsHelper.get(key);
                        if (webView != null) {
                            webView.loadUrl(JsHelper.createCallback(key, msg));
                        }
                        break;
                }
            } catch (Exception e) {
                HybridGlobal.logger.log(e);
            }
        }
        if (shouldFinish) {
            this.finish();
        }
    }


    private void takeCall(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + phone));
        startActivity(intent);
    }

    private void doLoadAudio() {
        MediaPlayerHelper helper = HybridGlobal.getInstance().getSoundHelper();
        String src = params.optString("src");
        String key = params.optString("key");
        String result = "";
        try {
            if (StringUtils.isNotBlank(src) && StringUtils.isNotBlank(key)) {
                SoundItem soundItem = new SoundItem();
                soundItem.setSoundPath(params.optString("src"));
                helper.loadSoundByPath(params.optString("key"), soundItem);

                params.put("success", true);
            } else {
                params.put("success", false);
            }
            result = params.toString();
        } catch (Exception e) {
            HybridGlobal.logger.log(e);
            result = "{\"success\": false}";
        }
        HybridGlobal.getCurrentWebView().loadUrl(JsHelper.createCallback("loadaudio", result));
    }

    private void goScanQRCode() {
        Intent intent = new Intent(me, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SCANQRCODE);
    }

    private void showImages() {
        try {
            JSONArray imageArray = params.optJSONArray("images");
            int index = params.optInt("index", 0);
            if (imageArray.length() > 0) {
                JSONArray finalImageArray = new JSONArray();
                for (int i = 0; i != imageArray.length(); i++) {
                    String url = imageArray.getJSONObject(i).optString("url", "");
                    if (StringUtils.isBlank(url)) {
                        continue;
                    }
                    finalImageArray.put(imageArray.getJSONObject(i));
                }
                Intent imageIntent = new Intent(this, ViewPagerActivity.class);
                imageIntent.putExtra("imageList", imageArray.toString());
                imageIntent.putExtra("index", index);
                startActivity(imageIntent);
            }
        } catch (Exception e) {
            HybridGlobal.logger.log(e);
        }
    }

    private void showNewWin() {
        // 打开新窗口
        Bundle webViewBundle = new Bundle();
        String typeTag = params.optString("type_tag", "");
        Boolean showNativeTopbar = params.optBoolean("native_topbar", false);
        String project = params.optString("project", "");
        String page = params.optString("page", "");
        String paramsData = params.optString("params", "{}");
        String title = params.optString("title", "");

        if (StringUtils.isBlank(project) || StringUtils.isBlank(typeTag) || StringUtils.isBlank(page)) {
            Context context = HybridGlobal.webViewStack.peek().getContext();
            Toast.makeText(context, R.string.error_newwin_params, Toast.LENGTH_SHORT).show();
        } else {
            webViewBundle.putString("typeTag", typeTag);
            webViewBundle.putBoolean("showTopbar", showNativeTopbar);
            webViewBundle.putString("linkurl", page);
            webViewBundle.putString("title", title);
            webViewBundle.putString("page", page);
            webViewBundle.putString("paramsdata", paramsData);
            webViewBundle.putString("project", project);

            Intent webViewIntent = new Intent(this, WebViewActivity.class);
            webViewIntent.putExtras(webViewBundle);
            startActivity(webViewIntent);
        }
    }

    private void cancelAllWebview() {
        WebViewBundle.getInstance().setBundle(params.toString());
        while (HybridGlobal.webViewStack.size() > 1) {
            Activity context = HybridGlobal.getCurrentWebViewContext();
            if (context != null) {
                context.finish();
            }
            HybridGlobal.webViewStack.pop();
        }
    }

    private void cancelWebview() {
        WebViewBundle.getInstance().setBundle(params.toString());
        Activity context = HybridGlobal.getCurrentWebViewContext();
        if (context != null) {
            context.finish();
        }
        HybridGlobal.webViewStack.pop();
    }

    /**
     * 启动拍照
     */
    private void doTakePhoto() {
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        photoPath = generateTempPhotoPath();
        File file = new File(photoPath);
        file.deleteOnExit();
        file.getParentFile().mkdirs();
        Uri fileUri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(intent, REQUEST_CODE_CAMERA);
    }

    private String generateTempPhotoPath() {
        return HybridGlobal.getTempFolder().getAbsolutePath() + File.separator + System.currentTimeMillis() + ".jpg";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_CAMERA) {
            JSONObject result = new JSONObject();
            File file = new File(photoPath);

            try {
                if (!file.exists()) {
                    result.put("success", false);
                    result.put("filepath", "");
                } else {
                    // 添加压缩图片逻辑
                    File destFile = new File(generateTempPhotoPath());
                    FileUtil.compressImage(file, destFile, 70);
                    result.put("success", true);
                    result.put("filepath", destFile.getAbsolutePath());
                }
            } catch (Exception e) {
                HybridGlobal.logger.log(e);
            }
            HybridGlobal.getCurrentWebView().loadUrl(JsHelper.createCallback("takephoto", result.toString()));
            photoPath = null;
            this.finish();
        } else if (requestCode == REQUEST_CODE_SCANQRCODE) {
            String code = data.getStringExtra("code");
            String result = "{\"success\": false}";
            if (StringUtils.isNotBlank(code)) {
                result = "{\"success\": true, \"code\": \"" + code + "\"}";
            }
            HybridGlobal.getCurrentWebView().loadUrl(JsHelper.createCallback("scanqrcode", result));
            this.finish();
        }
    }

    // FIXME 会在非照相请求中被调用
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        HybridGlobal.logger.log("onWindowFocusChanged:" + hasFocus);
        if (hasFocus) {
            JSONArray result = new JSONArray();
            try {
                ArrayList<String> paths = ImagePickResult.getInstance().getImageList();
                if (paths.size() > 0) {
                    //添加，去重
                    ArrayList<String> imagePathList = new ArrayList<>();
                    for (String path : paths) {
                        if (!imagePathList.contains(path)) {
                            imagePathList.add(path);
                        }
                    }
                    for (String path : imagePathList) {
                        JSONObject item = new JSONObject();

                        // 添加压缩图片
                        File destFile = new File(generateTempPhotoPath());
                        FileUtil.compressImage(new File(path), destFile, 70);

                        item.put("filepath", destFile.getAbsolutePath());
                        result.put(item);
                    }
                }
                ImagePickResult.getInstance().clearImageList();
            } catch (Exception e) {
                HybridGlobal.logger.log(e);
            }
            HybridGlobal.logger.log("takealbum:" + result.toString());
            HybridGlobal.getCurrentWebView().loadUrl(JsHelper.createCallback("takealbum", result.toString()));
            this.finish();
        }
    }

    private void logRequest(Uri uri) {
        StringBuilder sb = new StringBuilder();
        sb.append("url: ").append(uri.toString())
                .append("\nscheme: ").append(uri.getScheme())
                .append("\nhost: ").append(uri.getHost())
                .append("\npath: ");
        List<String> pathSegments = uri.getPathSegments();
        for (int i = 0; pathSegments != null && i < pathSegments.size(); i++) {
            sb.append("/").append(pathSegments.get(i));
        }
        // Query部分
        sb.append("\nquery: ").append(uri.getQuery());

        HybridGlobal.logger.log(sb.toString());
    }
}
